package main

import (
	"fmt"
	"time"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

type Student struct {
	ID         int32     `gorm:"primary_key;column:id"`
	Name       string    `gorm:"column:name"`
	Age        int32     `gorm:"column:age"`
	ModifyTime time.Time `gorm:"column:mtime"`
	Text       []byte    `gorm:"type:text"`
}

func (m *Student) TableName() string {
	return "student"
}

func (m Student) String() string {
	return fmt.Sprintf("ID:%d, Name:%s, Age:%d, ModifyTime:%s, Text:%s",
		m.ID, m.Name, m.Age, m.ModifyTime, string(m.Text))
}

func main() {
	mysql, err := gorm.Open("mysql", "root:nikki@(127.0.0.1:3306)/student?timeout=5s&parseTime=true&loc=Local&charset=utf8")
	if err != nil {
		panic(err)
	}

	// Conf
	mysql.DB().SetMaxIdleConns(5)
	mysql.DB().SetMaxOpenConns(10)
	mysql.LogMode(false)
	defer mysql.Close()

	mysql.AutoMigrate(&Student{})

	// Create
	student1 := Student{ID: 10004, Name: "Loft", Age: 23, ModifyTime: time.Now(), Text: []byte("TextString")}
	if err := mysql.Create(&student1).Error; err != nil {
		fmt.Println(err)
	}

	// Create Auto Increment
	student2 := Student{ID: 0, Name: "Astone", Age: 23, ModifyTime: time.Now(), Text: []byte("Astone String")}
	if err := mysql.Create(&student2).Error; err != nil {
		fmt.Println(err)
	}

	// Read
	fmt.Println("-----------Find-----------")
	StudentTable := make([]Student, 0)
	mysql.Find(&StudentTable)
	for _, val := range StudentTable {
		fmt.Println(val)
	}

	// Read
	fmt.Println("------Find Not Exists------")
	student3 := Student{ID: -1, Name: "Astone", Age: 23, ModifyTime: time.Now().Truncate(time.Second)}
	o := mysql.Where("id=?", student3.ID).First(&student3)
	if !o.RecordNotFound() {
		panic("unexpected error")
	}
	if student3.ID != -1 || student3.Name != "Astone" {
		panic("unexpected value")
	}
	fmt.Println(student3)

	// Update
	fmt.Println("-----------Modify-----------")
	student1.Age = 25
	mysql.Save(&student1)
	mysql.Find(&StudentTable)
	for _, val := range StudentTable {
		fmt.Println(val)
	}

	// Delete
	fmt.Println("-----------Delete-----------")
	mysql.Delete(&student1)
	mysql.Find(&StudentTable)
	for _, val := range StudentTable {
		fmt.Println(val)
	}

	// Delete
	fmt.Println("-----------Delete-----------")
	mysql.Delete(&student2)
	mysql.Find(&StudentTable)
	for _, val := range StudentTable {
		fmt.Println(val)
	}
}
